<template>
  <TablePage>
    <template #top>
      <SearchForm
        :title="t('routes.announcementManage')"
        :add-btn-text="t('aiot.notifiManage.add')"
        :keyword-search-data="searchModel"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        :del-btn-oper-type="OperPermissionType.MANAGE"
        :select-data="selectData"
        del-btn-text="删除公告"
        :del-btn-props="{ onClick: batchDelfn, disabled: selectedNotifiArr.length === 0 }"
        @add="showCreateModal"
        @search="handleSearch"
      />
    </template>
    <SlTable
      :columns="columns"
      row-key="id"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="pagination"
      :scroll="{ x: 'auto' }"
      :row-selection="rowSelection"
      :search-model="applySearchModel"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <a-space v-if="column.key === 'oper'">
          <PermissionBtn
            v-if="record.sendState !== 'SENT'"
            :btn-props="{ type: 'link', disabled: record.sendState === 'SENT' }"
            :oper-type="OperPermissionType.MANAGE"
            @click="showUpdateModal(record)"
            >{{ t("common.edit") }}</PermissionBtn
          >
          <DropdownOper
            v-if="record.sendState !== 'SENT'"
            v-model:visible="record.operVisible"
            :record="record"
            :data="operBtnData"
          >
          </DropdownOper>
        </a-space>
        <a v-else-if="column.dataIndex === 'title'" href="javascript:void(0)" @click="showDetailFn(record)">
          <EllipsisText :max-len="30" :text="record.title" />
        </a>
        <!-- <a-tag v-if="column.dataIndex === 'sendState'" :color="stateColor[record.sendState]">{{
          stateName[record.sendState]
        }}</a-tag> -->
        <StateTag
          v-if="column.dataIndex === 'sendState'"
          :color="stateColor[record.sendState]"
          :value="stateName[record.sendState]"
        ></StateTag>
      </template>
    </SlTable>
    <CURDDialog
      id-key="id"
      :columns="columns"
      :create-title="t('aiot.notifiManage.add')"
      :update-title="t('aiot.notifiManage.edit')"
      :check-title="t('aiot.notifiManage.detail')"
      :delete-message="t('aiot.notifiManage.delMsg')"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="functionBeforeOk"
      @before-show="beforeShow"
    />
    <CreateNotifiFullModal
      v-model:visible="addVisible"
      v-model:update-model="updateModel"
      :is-add="isAdd"
      :is-aiot="_isAiot"
      @ok="handleSuccessFn"
    />
    <MessageDetail v-model:visible="detailVisible" v-model:message="messageModal" :advice-type="adviceType" />
  </TablePage>
</template>
<script lang="ts" setup>
import { ref, onMounted, computed, createVNode } from "vue";
import { useI18n } from "/@/locales/useI18n";
import {
  Api,
  companyBatchDelete,
  companyDelete,
  companyPublish,
  platformBatchDelete,
  platformDelete,
  platformPublish,
} from "/@/api/aiot/notifiManage";
import SearchForm from "/@/components/SearchForm.vue";
import { useCURD } from "/@/hooks/useCURD";
import { enumToOptions } from "/@/utils/common";
import { OperPermissionType } from "/@/api/aiot/role/models";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import CreateNotifiFullModal from "./CreateNotifiFullModal.vue";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  OperItem,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import TablePage from "/@/components/TablePage.vue";
import SlTable from "/@/components/SlTable.vue";
import { OrderRule, TableRecord } from "/@/api/models";
import { NotifiReqItem, NotifiStatus } from "/@/api/aiot/notifiManage/models";
import type { PartialNotifiItem } from "/@/api/aiot/notifiManage/models";
import InfoModal from "/@/components/InfoModal";
import { message } from "ant-design-vue";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import { SelectItem } from "/@/types/components";

const props = defineProps<{
  isAiot: boolean;
}>();
const _isAiot = computed(() => {
  return props.isAiot;
});
const adviceType = computed(() => {
  return props.isAiot ? "PLATFORM" : "COMPANY";
});
const { t } = useI18n();
const isAdd = ref<boolean>(true);
const stateColor = { DRAFT: "#F56D6A", SENT: "#38CE7B" };
const stateName = { DRAFT: "草稿", SENT: "发布" };
const updateModel = ref<PartialNotifiItem>({});
const detailVisible = ref<boolean>(false);
const messageModal = ref<PartialNotifiItem>({});

const columns: Array<TableRecord> = [
  {
    title: t("aiot.notifiManage.title"),
    dataIndex: "title",
    ellipsis: true,
  },
  {
    title: t("aiot.notifiManage.sendState"),
    dataIndex: "sendState",
    ellipsis: true,
    width: "200px",
  },
  {
    title: "发布时间",
    dataIndex: "sendTime",
    ellipsis: true,
    sorter: true,
    width: "200px",
  },
  {
    title: "发布人",
    dataIndex: "sender",
    width: "200px",
    ellipsis: true,
  },
  {
    title: t("common.oper"),
    key: "oper",
    width: "100px",
    fixed: "right",
  },
];
const model = ref<PartialNotifiItem>({
  title: "",
  content: "",
});
const modelFormSetting: FormItemData[] = [
  {
    key: "title",
    label: t("aiot.notifiManage.title"),
    max: 32,
    required: true,
  },
  {
    label: t("aiot.notifiManage.content"),
    key: "content",
    max: 1000,
    type: FormItemComponentType.TEXTAREA,
  },
];

const showOptions = ref<ShowCURDModalOptions>();
const addVisible = ref<boolean>(false);
const curSelectedRow = ref<PartialNotifiItem>({});
const selectedNotifiArr = ref<string[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: string[], selectedRows: PartialNotifiItem[]) => {
    selectedNotifiArr.value = selectedRowKeys;
  },
  getCheckboxProps: (record: PartialNotifiItem) => ({
    disabled: record.sendState === "SENT", // Column configuration not to be checked
  }),
};
function showCreateModal() {
  updateModel.value = {};
  isAdd.value = true;
  addVisible.value = true;
}
onMounted(() => {
  reloadTable({ current: 1 });
  // reloadTable({ current: 1 });
});
function beforeShow(e) {
  if (e.action === CURDAction.UPDATE || e.action === CURDAction.CHECK) {
  }
}
const searchModel = [{ key: "title", label: t("aiot.notifiManage.searchText") }];
const selectData = ref<SelectItem[]>([
  {
    label: "状态",
    value: "",
    key: "sendState",
    props: { allowClear: false },
    options: enumToOptions(NotifiStatus, "notifiStatus"),
  },
]);
selectData.value[0].options?.unshift({ label: "全部", value: "" });
function handleSearch(model) {
  reloadTable({ model, current: 1 });
}
function handleSuccessFn() {
  addVisible.value = false;
  reloadTable({ current: 1 });
}
function showDetailFn(row) {
  messageModal.value = row;
  detailVisible.value = true;
}
const {
  tableData,
  tableLoading,
  curd,
  reloadTable,
  pagination,
  searchModel: applySearchModel,
} = useCURD<NotifiReqItem>({
  getPageUrl: props.isAiot ? Api.platformPage : Api.getNotifiPage,
  deleteMethod: RequestMethodEnum.DELETE,
  deleteUrl: props.isAiot ? Api.platformBatchDelete : Api.companyBatchDelete,
  loadOnMounted: false,
});

const operData: OperItem<NotifiReqItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
    disabledMes: (record) => (record.sendState === "SENT" ? t("aiot.notifiManage.disMsg") : ""),
  },
  {
    label: t("common.delete"),
    type: "primary",
    danger: true,
    disabledMes: (record) => (record.sendState === "SENT" ? t("aiot.notifiManage.disMsg") : ""),
    handler: deleteRecord,
  },
];
const operBtnData: OperItem<TableRecord>[] = [
  {
    label: t("aiot.notifiManage.publish"),
    operType: OperPermissionType.MANAGE,
    disabledMes: (record) => (record.sendState === "SENT" ? t("aiot.notifiManage.disMsg") : ""),
    handler: (record) => {
      // platformPublish
      InfoModal.info({
        content: t("aiot.notifiManage.sendMsg"),
        async onOk() {
          let result: boolean | null;
          if (props.isAiot) {
            result = await platformPublish({ id: record.id });
          } else {
            result = await companyPublish({ id: record.id });
          }
          if (result) {
            message.success(t("common.operSuccess"));
            await reloadTable();
          }
        },
      });
    },
  },
  {
    label: t("common.delete"),
    type: "primary",
    operType: OperPermissionType.MANAGE,
    disabledMes: (record) => (record.sendState === "SENT" ? t("aiot.notifiManage.disMsg") : ""),
    // permissionCode: PermissionCode.USER_DELETE,s
    danger: true,
    handler: async (record) => {
      InfoModal.warningConfirm({
        content: "您确定要删除该公告吗？",
        okText: "删除",
        async onOk() {
          let req: boolean;
          if (props.isAiot) {
            req = (await platformDelete(record.id)) || false;
          } else {
            req = (await companyDelete(record.id)) || false;
          }
          if (req) {
            message.success("操作成功");
            reloadTable();
          }
        },
      });
    },
  },
];
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}
function showUpdateModal(record) {
  // showOptions.value = { action: CURDAction.UPDATE, record };
  isAdd.value = false;
  updateModel.value = record;
  addVisible.value = true;
}
function deleteRecord(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function functionBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as NotifiReqItem;
  }
}
// 项目切换计划时间
function handleTableChange(pag: { pageSize: number; current: number }, filters: any, sorter: any) {
  if (sorter.field === "sendTime") {
    let obj = { sort: "sendTime", order: OrderRule.ASC };
    if (sorter.order === "ascend") {
      obj.order = OrderRule.ASC;
    } else if (sorter.order === "descend") {
      obj.order = OrderRule.DESC;
    } else {
      obj.order = OrderRule.ASC;
    }
    reloadTable(obj);
  }
}
async function batchDelfn() {
  InfoModal.confirm({
    content: "您确定要删除已选公告吗？",
    async onOk() {
      let req: boolean;
      if (props.isAiot) {
        req = (await platformBatchDelete({ ids: selectedNotifiArr.value })) || false;
      } else {
        req = (await companyBatchDelete({ ids: selectedNotifiArr.value })) || false;
      }
      if (req) {
        message.success("操作成功");
        reloadTable();
        selectedNotifiArr.value = [];
      }
    },
  });
}
</script>

<style lang="less">
:deep(.ant-modal-confirm-body > .anticon) {
  color: red !important;
}
</style>
